package com.saifan.wyy_ov.ui.onlishop;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.common.IconText;
import com.saifan.wyy_ov.data.bean.CommonDataBean;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.data.bean.PopBean;
import com.saifan.wyy_ov.data.bean.StoreBean;
import com.saifan.wyy_ov.data.bean.StoreDetailBean;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.IListViewOnClick;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.album.ui.PhotoAlbumActivity;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.CircleImageView;
import com.saifan.wyy_ov.ui.view.NoScrollListView;
import com.saifan.wyy_ov.utils.CallPhoneUtil;
import com.saifan.wyy_ov.utils.CameraUtil;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.ImgUtil;
import com.saifan.wyy_ov.utils.PopUtil;
import com.saifan.wyy_ov.utils.PriceUtils;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import lomasky.ma.utils.DensityUtil;
import lomasky.ma.utils.SharedPrefUtil;

/**
 * @author WangLi
 * @version V1.0
 * @date 2015年3月14日 下午12:46:21
 * @Description 店铺详情
 */

public class StoreDetailsActivity extends BaseActivity implements View.OnClickListener {
    private static final int CALL_PHONE = 123;
    private RelativeLayout loadingLayout;
    private NoScrollListView listView;
    private CommonAdapter<StoreDetailBean.Goods> adapter;
    private IGetData getData;
    private CommonDataBean requestBean;
    private ImageView storeBg;
    private CircleImageView storeImg;
    private TextView storeName;
    private TextView storeType;
    private TextView note;
    private TextView time;
    private CheckBox shoucang;
    private TextView address;
    private Button tel;

    private TextView comment;
    private LinearLayout getmoreView;
    private StoreBean bean;
    private StoreDetailBean data;
    private List<StoreDetailBean.Goods> list;
    private Toolbar toolbar;
    private ListPopupWindow listPopupWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store_details);
        bean = (StoreBean) getIntent().getSerializableExtra("data");
        getData = new GetData();
        requestBean = new CommonDataBean();
        requestBean.setCustomerID(getRoomInfoBean().getWYKHDA_ZJ());
        requestBean.setPage(0);
        requestBean.setID(bean.getID());
        requestBean.setStoreId(String.valueOf(bean.getID()));
        findViews();
        setupViews();
        getDataInit();
        initPopList();
    }

    private void initPopList() {
        listPopupWindow = new ListPopupWindow(this);
        lomasky.ma.xui.CommonAdapter adapter = new lomasky.ma.xui.CommonAdapter<IconText>(this, R.layout.pop_item) {
            @Override
            public void onBind(lomasky.ma.xui.ViewHolderHelper holder, IconText iconText, int i) {
                holder.setImage(R.id.pop_img, iconText.icon);
                holder.setText(R.id.pop_text, iconText.text);
            }
        };
        List<IconText> list = new ArrayList<>();
        list.add(new IconText(R.mipmap.home_insidepage, "商城首页"));
        list.add(new IconText(R.mipmap.cart_insidepage, "我的购物车"));
        list.add(new IconText(R.mipmap.indent_insidepage, "我的订单"));
        list.add(new IconText(R.mipmap.collect_insidepage, "我的收藏"));
        adapter.setData(list);

        listPopupWindow.setAdapter(adapter);
        listPopupWindow.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = null;
                switch (position) {
                    case 0:
                        intent = new Intent(StoreDetailsActivity.this, OnlineShopActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                        break;
                    case 1:
                        intent = new Intent(StoreDetailsActivity.this, MyCartActivity.class);
                        break;
                    case 2:
                        intent = new Intent(StoreDetailsActivity.this, MyOrderActivity.class);
                        break;
                    case 3:
                        intent = new Intent(StoreDetailsActivity.this, MyCollectActivity.class);
                        break;
                    default:
                        break;
                }
                if (intent != null) {
                    startActivity(intent);
                }
                listPopupWindow.dismiss();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.store_details, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_more) {
            listPopupWindow.setAnchorView(toolbar);
            listPopupWindow.setWidth(DensityUtil.getWidth(this) / 2);
            listPopupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
            listPopupWindow.setHorizontalOffset(DensityUtil.getWidth(this) / 2);
            listPopupWindow.show();


        }
        return super.onOptionsItemSelected(item);
    }

    @SuppressLint("InflateParams")
    private void findViews() {
        getmoreView = (LinearLayout) findViewById(R.id.get_more);
        getmoreView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StoreDetailsActivity.this, OtherGoodsActivity.class);
                intent.putExtra("ID", bean.getID());
                intent.putExtra("type", "全部");
                intent.putExtra("storeId", String.valueOf(bean.getID()));
                startActivity(intent);
            }
        });
        loadingLayout = (RelativeLayout) findViewById(R.id.loading_lay);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        listView = (NoScrollListView) findViewById(R.id.listView);

        storeBg = (ImageView) findViewById(R.id.store_bg);
        storeImg = (CircleImageView) findViewById(R.id.store_img);
        storeName = (TextView) findViewById(R.id.store_name);
        storeType = (TextView) findViewById(R.id.store_type);
        note = (TextView) findViewById(R.id.note);
        time = (TextView) findViewById(R.id.time);
        shoucang = (CheckBox) findViewById(R.id.shoucang);
        address = (TextView) findViewById(R.id.address);
        tel = (Button) findViewById(R.id.tel);

        comment = (TextView) findViewById(R.id.comment);


        shoucang.setOnClickListener(this);
        tel.setOnClickListener(this);
        comment.setOnClickListener(this);

        list = new ArrayList<StoreDetailBean.Goods>();
        adapter = new CommonAdapter<StoreDetailBean.Goods>(StoreDetailsActivity.this, list, R.layout.goods_item) {
            @Override
            public void convert(ViewHolderHelper helper, StoreDetailBean.Goods item) {
                helper.setText(R.id.goods_name, StringUtil.returnShow(item.getGoodsName()));
                helper.setText(R.id.goods_category, StringUtil.returnShow(item.getGoodsType()));
                helper.setText(R.id.goods_price, "店铺价: " + PriceUtils.getPrice(item.getGoodsPrice()));
                helper.setText(R.id.sales, "已售: " + StringUtil.returnShow(item.getSold()));
                helper.setImageByUrl(R.id.goods_img, item.getCoverPhoto());
            }
        };

        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                Intent intent = new Intent(StoreDetailsActivity.this, GoodsDetailActivity.class);
                intent.putExtra("storeId", String.valueOf(bean.getID()));
                intent.putExtra("goodsId", data.getGoodsList().get(arg2).getID());
                intent.putExtra("goodsName", data.getGoodsList().get(arg2).getGoodsName());
                intent.putExtra("price", data.getGoodsList().get(arg2).getGoodsPrice());
                startActivity(intent);
            }
        });
        listView.setFocusable(false);

    }

    private void setupViews() {
        if (bean != null) {
            storeName.setText(StringUtil.returnShow(bean.getStoreName()));
            String datesString = "", timeString = "";
            if (!StringUtil.isNullOrEmpty(bean.getBusinessDate())) {
                datesString = bean.getBusinessDate().replace(",", "至");
            }
            if (!StringUtil.isNullOrEmpty(bean.getBusinessTime())) {
                timeString = bean.getBusinessTime().replace(",", "至");
            }
            time.setText("营业时间:  " + datesString + " " + timeString);
            storeType.setText(StringUtil.returnShow(bean.getStoreType()));
            if (bean.isIsDelivery()) {
                note.setText("配送标准:  " + StringUtil.returnShow(String.valueOf(bean.getDeliveryAmount())) + "元起送/"
                        + StringUtil.returnShow(bean.getDeliveryInstructions()));
            } else {
                note.setText("配送标准:  不支持送货");
            }

            tel.setText("联系商家:  " + bean.getTel());
            ImgUtil.DisPlayImg(bean.getHeadPhoto(), storeBg, StoreDetailsActivity.this);
            ImgUtil.DisPlayImg(bean.getHeadPhoto(), storeImg, StoreDetailsActivity.this);
            address.setText(StringUtil.returnShow(bean.getAddress()));


        }
    }

    private void getDataInit() {
        getData.getDataJson(StoreDetailsActivity.this, Api.StoreList.STOREDETAIL, requestBean, "", new ResponseData() {

            @SuppressLint("NewApi")
            @Override
            public void onSuccess(String json) {
                loadingLayout.setVisibility(View.GONE);
                List<StoreDetailBean> dataList = new ArrayList<StoreDetailBean>();
                dataList = new Gson().fromJson(json, new TypeToken<List<StoreDetailBean>>() {
                }.getType());
                if (dataList.size() > 0) {
                    data = dataList.get(0);
                    if (data != null) {

                        if (data.isIsCollect()) {
                            shoucang.setChecked(true);
                        } else {
                            shoucang.setChecked(false);
                        }
                        list = data.getGoodsList();
                        if (list.size() > 4) {
                            list = data.getGoodsList().subList(0, 4);
                            getmoreView.setVisibility(View.VISIBLE);
                        } else {
                            list = data.getGoodsList();
                        }
                        adapter.mDatas = list;
                        adapter.notifyDataSetChanged();
                    }
                }

            }

            @Override
            public void onFailed(String str) {
                loadingLayout.setVisibility(View.GONE);
            }
        });
    }

    public void onClick(View v) {
        if (v == shoucang) {
            if (getRoomInfoBean().getUserType() == 2) {
                for (PermissionsBean permissionsBean : getPermissions()) {
                    if (permissionsBean.getYKQX_GNMC().equals("在线商城")) {
                        shoucangStore();
                        return;
                    }
                }
                shoucang.setChecked(!shoucang.isChecked());
                ToastUtil.showToast(StoreDetailsActivity.this, "您的权限不能进行此操作");
                return;
            } else if (getRoomInfoBean().getUserType() == 3) {
                shoucang.setChecked(!shoucang.isChecked());
                ToastUtil.showToast(StoreDetailsActivity.this, "您的权限不能进行此操作");
                return;
            }

            shoucangStore();
        } else if (v == tel) {
//            TelUtil.callPhone(StoreDetailsActivity.this, tel.getText().toString().replace("联系商家:  ", ""));
            if (Build.VERSION.SDK_INT >= 23) {

                int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
                    return;
                } else {

                    CallPhoneUtil.callPhone( this,   bean.getTel() );


                }
            } else {

                CallPhoneUtil.callPhone( this,   bean.getTel() );


            }

        } else if (v == comment) {
            Intent intent = new Intent(StoreDetailsActivity.this, CommentsActivity.class);
            intent.putExtra("ID", bean.getID());
            startActivity(intent);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == CALL_PHONE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
//                Intent phoneIntent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + bean.getTel()));
//                startActivity(phoneIntent);
                CallPhoneUtil.callPhone( this,   bean.getTel() );


            } else {
                // Permission Denied
                Toast.makeText(this, "您禁用拨打电话权限", Toast.LENGTH_SHORT)
                        .show();

            }
        }

    }

    private void shoucangStore() {
        String method = "";
        if (data == null) {
            return;
        }
        if (data.isIsCollect()) {
            method = Api.StoreList.CANCELCOLLECT;
        } else {
            method = Api.StoreList.COLLECTSUBMIT;
        }
        getData.getDataJson(StoreDetailsActivity.this, method, requestBean, "正在请求...", new ResponseData() {

            @SuppressLint("NewApi")
            @Override
            public void onSuccess(String json) {
                if (data.isIsCollect()) {
                    data.setIsCollect(false);
                    shoucang.setChecked(false);
                    ToastUtil.showToast(StoreDetailsActivity.this, "取消收藏成功");
                } else {
                    data.setIsCollect(true);
                    shoucang.setChecked(true);
                    ToastUtil.showToast(StoreDetailsActivity.this, "收藏成功");
                }
            }

            @Override
            public void onFailed(String str) {
            }
        });
    }
}
